﻿using FinancialManagement.Application.Command.ActualRefundCommand;
using FinancialManagement.Domain.Model;
using FinancialManagement.Infrstructre.Interface;
using MediatR;
using SqlSugar;

namespace FinancialManagement.Application.CommandHandler.ActualRefundCommandHandler
{
    public class UpdActualRefundCommandHandler : IRequestHandler<UpdActualRefundCommand, int>
    {

        ISalesShouldRefundRepository ssrRep;
        ISalesReturnRepository srRep;
        ISqlSugarClient db;

        public UpdActualRefundCommandHandler(ISalesShouldRefundRepository ssrRep, ISalesReturnRepository srRep, ISqlSugarClient db)
        {
            this.ssrRep = ssrRep;
            this.srRep = srRep;
            this.db = db;
        }

        public async Task<int> Handle(UpdActualRefundCommand request, CancellationToken cancellationToken)
        {
            // 开始事务
            db.Ado.BeginTran();

            try
            {
                //修改
                var list = await ssrRep.UpdateAsync(new SalesShouldRefund
                {
                    SalesShouldRefundId = request.SalesShouldRefundId,
                    RefundPlanCode = Guid.NewGuid().ToString(),
                    PlanRefundDate = request.PlanRefundDate,
                    RefundPaceWay = 1,
                    AmountRefund = request.AmountRefund,
                    SalesReturnId = request.SalesReturnId
                });

                var salesreturn = (from sr in await srRep.GetAllAsyns() select sr).ToList();
                var salesshould = (from ssr in await ssrRep.GetAllAsyns() select ssr).ToList();
                var fan = (from sr in salesreturn
                           where sr.SalesReturnId == request.SalesReturnId
                           select new SalesReturn
                           {
                               SalesReturnId = sr.SalesReturnId,
                               SalesReturnCode = sr.SalesReturnCode,
                               SalesReturnTopic = sr.SalesReturnTopic,
                               SalesReturnDate = sr.SalesReturnDate,
                               ClientId = sr.ClientId,
                               SalesReturnState = sr.SalesReturnState,
                               SalesReturnAmout = sr.SalesReturnAmout,
                           }).First();

                fan.SalesReturnAmout -= request.AmountRefund;
                await srRep.UpdateAsync(fan);


                // 提交事务
                db.Ado.CommitTran();

                return 1;  // 返回最终的结果
            }
            catch (Exception)
            {
                // 回滚事务
                db.Ado.RollbackTran();
                throw;
            }
        }
    }
}
